package com.xkcyy.one.ai.common.tool;

import com.fasterxml.jackson.databind.JsonNode;
import com.xkcyy.one.ai.llm.model.ToolDefinition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * HTTP工具实现
 * 
 * @author yuand
 */
@Slf4j
public class HttpTool extends AbstractTool {
    private final RestTemplate restTemplate;

    public HttpTool(ToolDefinition definition, RestTemplate restTemplate) {
        super(definition);
        this.restTemplate = restTemplate;
    }

    @Override
    protected String executeInternal(String inputParams) {
        try {
            JsonNode params = objectMapper.readTree(inputParams);
            String url = params.get("url").asText();
            String method = params.get("method").asText();
            JsonNode headers = params.get("headers");
            JsonNode body = params.get("body");

            HttpHeaders httpHeaders = new HttpHeaders();
            if (headers != null) {
                headers.fields().forEachRemaining(entry -> httpHeaders.add(entry.getKey(), entry.getValue().asText()));
            }

            HttpEntity<String> requestEntity = new HttpEntity<>(
                    body != null ? body.toString() : null,
                    httpHeaders);

            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.valueOf(method.toUpperCase()),
                    requestEntity,
                    String.class);

            return response.getBody();
        } catch (Exception e) {
            log.error("Error executing HTTP tool", e);
            throw new RuntimeException("Failed to execute HTTP tool", e);
        }
    }

    @Override
    public String getType() {
        return "http";
    }
}